// app/controller/users.js
const Controller = require('egg').Controller;

const { PrismaClient } = require('@prisma/client');
// // 注意删除临时文件
// await fs.unlink(file.filepath);

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class UserController extends Controller {
  constructor(props) {
    super(props);
    this.prisma = new PrismaClient();
  }

  // get
  async index() {
    const ctx = this.ctx;
    const res = await this.prisma.instruction.findMany({});
    ctx.status = 200;
    ctx.body = {
      code: 0,
      data: res,
      success: true,
    };
  }

  // get /:id
  async show() {
    const ctx = this.ctx;
    // ctx.params.id
    const res = await this.prisma.instruction.findUnique({
      where: {
        id: toInt(ctx.params.id),
      },
    });
    ctx.status = 200;
    ctx.body = {
      code: 0,
      data: res,
      success: true,
    };
  }

  // post
  async create() {
    const ctx = this.ctx;
    const { name, instruction } = ctx.request.body;
    const res = await this.prisma.instruction.create({
      data: { name, instruction },
    });
    ctx.status = 200;
    ctx.body = {
      code: 0,
      data: res,
      status: 'success',
    };
  }

  async update() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const { name, instruction } = ctx.request.body;

    const res = await this.prisma.instruction.upsert({
      where: { id: parseInt(id) },
      update: { name, instruction },
      create: {
        name,
        instruction,
      },
    });
    ctx.status = 200;
    ctx.body = {
      code: 0,
      status: 'success',
      data: res,
    };
  }

  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const res = await this.prisma.instruction.delete({
      where: { id: parseInt(id) },
    });

    ctx.status = 200;
    ctx.body = {
      code: 0,
      data: res,
      status: 'success',
    };
  }
}

module.exports = UserController;
